package com.itheima.dubbo.mongodb.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.commons.model.mongo.Visitors;
import com.itheima.dubbo.interfaces.VisitorsApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public String saveVisitor(Visitors visitors) {
        // 先判断当天是否已经来访过
        Visitors one = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId()))
                .with(Sort.by(Sort.Order.desc("date")))
                .with(PageRequest.of(0, 1)), Visitors.class);

        // 如果已经来访过 就不在新增
        if (ObjectUtil.isNotEmpty(one) && DateUtil.isIn(DateUtil.date(one.getDate()), DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()))) {
            return one.getId().toHexString();
        }
        // 如果没有来访过 就新增
        return mongoTemplate.save(visitors).getId().toHexString();
    }

    @Override
    public List<Visitors> queryTopVisitor(Long userId, Long lastQueryDate) {
        if (ObjectUtil.isEmpty(lastQueryDate)) {
            // 之前没有查询过 取最近来访者前5条
            return mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                            .with(Sort.by(Sort.Order.desc("date")))
                            .with(PageRequest.of(0, 5))
                    , Visitors.class);
        }
        // 之前查询过来访者  取之前来访时间之后的前5条
        return mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)
                        .and("date").gt(lastQueryDate))
                        .with(Sort.by(Sort.Order.desc("date")))
                        .with(PageRequest.of(0, 5))
                , Visitors.class);
    }

    // 分页查询最近来访的人
    @Override
    public List<Visitors> queryVisitorByPages(Long userId, Integer page, Integer pageSize) {
        List<Visitors> visitors = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                        .with(Sort.by(Sort.Order.desc("date")))
                        .with(PageRequest.of(page - 1, pageSize))
                , Visitors.class);
        return visitors;
    }
}
